package compraventa.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import compraventa.modelo.Persona;
import compraventa.modelo.Publicacion;
import compraventa.negocio.GestionMovimientos;
import compraventa.negocio.GestionPublicacion;

/**
 * Servlet implementation class ComprarPublicacionServlet
 */
@WebServlet("/PublicacionComprarServlet")
public class PublicacionComprarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PublicacionComprarServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String sid = request.getParameter("id");
		int id = Integer.parseInt(sid);
		
		GestionPublicacion neg = new GestionPublicacion();
		try {
			Publicacion vo = neg.obtener(id);
			request.setAttribute("vo", vo);
			RequestDispatcher rd = request.getRequestDispatcher("scv_comprarpublicacion.jsp");
			rd.forward(request, response);
			
		} catch (Exception e) {
			request.setAttribute("error", e.getMessage());
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);
		}
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sid = request.getParameter("txtid");
		Integer idpub = Integer.parseInt(sid);
		Integer cant = Integer.parseInt(request.getParameter("Cantidad"));
		String com = request.getParameter("txtComentario");
		Integer idlogin = 0;
		GestionMovimientos movimientos = new GestionMovimientos();
		HttpSession session = request.getSession();
		try {
			Persona usuario_actual = (Persona)session.getAttribute("USUARIO");
			idlogin = usuario_actual.getIdPersona();
			movimientos.comprar(idpub, cant, com, idlogin);
			response.sendRedirect(request.getContextPath()	+ "/VentasOK.jsp");
		} catch (Exception e) {
			request.setAttribute("error", e.getMessage());
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);
		}
	}
}
